#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <stdarg.h>
#include <time.h>
#include <sys/time.h>
#include "../head/log.h"         //define 宏定义及static变量
#include "../head/default.h"         //define 宏定义及static变量
#ifndef LOGLEVEL
#define LOGLEVEL DEBUG  //最高日志级别debug
#endif
static const char *s_loginfo[] = { //日志级别
    [ERROR] = "ERROR",
    [WARN]  = "WARN",
    [INFO]  = "INFO",
    [DEBUG] = "DEBUG",
};

extern char log_file_path[VAR_MAX_LEN];

static void f_get_time(char *buffer) {
    time_t t;
    struct tm *p;
    struct timeval tv;
    int len;
    int millsec;

    t = time(NULL);
    p = localtime(&t);

    gettimeofday(&tv, NULL);
    millsec = (int)(tv.tv_usec / 1000);

    /* 时间格式：[2020-08-26 12:47:34:888] */
    len = snprintf(buffer, 32, "[%04d-%02d-%02d %02d:%02d:%02d:%03d] ", p -> tm_year + 1900, p -> tm_mon + 1, p -> tm_mday, p -> tm_hour, p -> tm_min, p -> tm_sec, millsec);

    buffer[len] = '\0';
}

void f_logging(enum LogLevel level, const char *fmt, ...) {
    if(level > LOGLEVEL) {
        return;
    }

    va_list arg_list;
    char buf[VAR_MAX_LEN];
    memset(buf, 0x00, sizeof(VAR_MAX_LEN));
    va_start(arg_list, fmt);
    vsnprintf(buf, VAR_MAX_LEN, fmt, arg_list);
    char time[32] = {0};
    f_get_time(time);
    char log_info[VAR_MAX_LEN + strlen(s_loginfo[level]) + strlen(time)];


    memset(log_info, 0x00, sizeof(log_info));
    sprintf(log_info,"%s[%s] %s", time, s_loginfo[level], buf);

    if (strcmp(s_loginfo[level], "ERROR") == 0) {
        printf("\033[31m%s\033[0m\n", log_info);
    } else if (strcmp(s_loginfo[level], "WARN") == 0) {
        printf("\033[33m%s\033[0m\n", log_info);
    } else {
        printf("\033[32m%s\033[0m\n", log_info);
    }

    FILE *fp = NULL;
    fp = fopen(log_file_path, "a");
    fprintf(fp, log_info);
    fprintf(fp, "\n");
    fclose(fp);
    va_end(arg_list);
}

